const { Op } = require('sequelize')
const { format } = require('date-fns');
const Chat = require('../model/Chat_model')

class ChatService {
    //创建聊天记录
    async CreateChar(params) {
        const { senderId, receiverId, type, message } = params
        const res = await Chat.create({ senderId, receiverId, type, message })
        const result = res.toJSON();
        result.createdAt = format(new Date(result.createdAt), 'yyyy-MM-dd HH:mm:ss');
        return result
    }

    async selectChat(params) {
        const { senderId, receiverId, pageSize, pageNo } = params
        const limit = pageSize * 1
        const offset = (pageNo * 1 - 1) * pageSize
        const { count, rows } = await Chat.findAndCountAll({
            attributes: ['chat_id', 'senderId', 'receiverId', 'type', 'message', 'createdAt'],
            where: {
                [Op.or]: [{ senderId, receiverId }, { senderId: receiverId, receiverId: senderId }]
            },
            order: [
                ['createdAt', 'DESC'],
            ],
            offset,
            limit
        })
        return { count, rows }
    }
}

module.exports = new ChatService()